﻿namespace YunQue.Common.Helpers
{
    /// <summary>
    /// 生成随机字符串帮助类
    /// </summary>
    public class RandomStrHelper
    {
        private const string _letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        private const string _numbers = "0123456789";
        private const string _specials = "!@#$%^&*()_+-=[]{}|;:,.<>?";
        /// <summary>
        /// 生成密码
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string GeneratePassword(int length = 13)
        {
            //长度不小于3位，包含大小写字母、数字、特殊字符
            if (length < 3)
            {
                throw new ArgumentException("密码长度不能小于3位");
            }
            char number= GetRandomChar(_numbers);
            char letter = GetRandomChar(_letters);
            char special = GetRandomChar(_specials);
            string allChars = _letters + _numbers + _specials;
            StringBuilder sb = new StringBuilder();
            sb.Append(number);
            sb.Append(letter);
            sb.Append(special);
            for (int i = 0; i < length - 3; i++)
            {
                sb.Append(GetRandomChar(allChars));
            }
            return sb.ToString();
        }
        /// <summary>
        /// 随机生成一个字符
        /// </summary>
        /// <param name="characterPool"></param>
        /// <returns></returns>
        private static char GetRandomChar(string characterPool)
        {
            byte[] randomBytes = new byte[4];
            RandomNumberGenerator.Fill(randomBytes);
            int randomIndex = BitConverter.ToInt32(randomBytes, 0) % characterPool.Length;
            return characterPool[Math.Abs(randomIndex)];
        }
    }
}
